<?php
//No direct access
defined('_JEXEC') or die('Restricted access');

jimport('joomla.application.component.model');

class OwnserviceModelUsers extends JModel
{
	/**
	 * Users data array
	 *
	 * @var array
	 */
	var $_data = null;

	/**
	 * Users total
	 *
	 * @var integer
	 */
	var $_total = null;

	/**
	 * Pagination object
	 *
	 * @var object
	 */
	var $_pagination = null;

	/**
	 * Constructor
	 *
	 * @since 1.5
	 */

	function __construct()
	{
		parent::__construct();

		global $mainframe,$option;

		$limit		= $mainframe->getUserStateFromRequest( $option.'.user.limit', 'limit', $mainframe->getCfg('list_limit'), 'int');
		$limitstart = $mainframe->getUserStateFromRequest( $option.'.user.limitstart', 'limitstart', 0, 'int' );
		
		$limitstart = ( $limit != 0 ? (floor($limitstart / $limit) * $limit) : 0 );

		$this->setState('limit', $limit);
		$this->setState('limitstart', $limitstart);
	}

	/**
	 * Method to get users data
	 *
	 * @access public
	 * @return array
	 */
	function getData() {

		// Lets load the users if it doesn't already exist
		if (empty($this->_data))
		{
			$query = $this->_buildQuery();
			$this->_data = $this->_getList($query, $this->getState('limitstart'), $this->getState('limit'));
		}

		return $this->_data;
	}

	/**
	 * Method to get the total number of users
	 *
	 * @access public
	 * @return integer
	 */
	function getTotal() {
		// Lets load the users if it doesn't already exist
		if (empty($this->_total))
		{
			$query = $this->_buildQuery();
			$this->_total = $this->_getListCount($query);
		}

		return $this->_total;
	}

	/**
	 * Method to get a pagination object for the users
	 *
	 * @access public
	 * @return object
	 */
	function getPagination() {

		// Lets load the customer account if it doesn't already exist
		if (empty($this->_pagination)) {
			jimport('joomla.html.pagination');
			$this->_pagination = new FMCPagination( $this->getTotal(), $this->getState('limitstart'), $this->getState('limit') );
		}

		return $this->_pagination;
	}

	/**
	 * Method to build the query for the users
	 *
	 * @access private
	 * @return integer
	 * @since 1.0
	*/
	function _buildQuery()
	{
		$user =& JFactory::getUser();
		$aid = $user->get('aid', 0);

		// Get the WHERE and ORDER BY clauses for the query
		$where		= $this->_buildContentWhere();
		$orderby	= $this->_buildContentOrderBy();

		//Query to retrieve all users that belong under the web links section and that are published.
		$query = ' SELECT p.*, u.username, u.email, g.name AS groupname FROM #__ownservice_users AS p '
				.' LEFT JOIN #__users AS u ON u.id=p.user_id '
				.' LEFT JOIN #__ownservice_groups AS g ON g.id=p.group_id '
				.$where
				.$orderby;

		return $query;
	}

	/**
	 * Method to build the orderby clause of the query for the users
	 *
	 * @access private
	 * @return string
	 * @since 1.0
	 */
	function _buildContentOrderBy(){
		global $mainframe, $option;

		$filter_order		= $mainframe->getUserStateFromRequest($option.'.user.filter_order', 'filter_order', 'p.firstname', 'cmd');
		$filter_order_Dir	= $mainframe->getUserStateFromRequest($option.'.user.filter_order_Dir', 'filter_order_Dir', '', 'cmd');

		$orderby 	= ' ORDER BY '.$filter_order.' '.$filter_order_Dir;

		return $orderby;
	}

	/**
	 * Method to build the where clause of the query for the users
	 *
	 * @access private
	 * @return string
	 * @since 1.0
	 */
	function _buildContentWhere()
	{
		global $mainframe, $option;

		// Initialise variables
		$user = & JFactory::getUser();

		$filter_group		= $mainframe->getUserStateFromRequest($option.'.user.filter_group', 'filter_group', 0, 'int');
		$filter_branch		= $mainframe->getUserStateFromRequest($option.'.user.filter_branch', 'filter_branch', 0, 'int');
		$search				= $mainframe->getUserStateFromRequest($option.".user.search", 'search', '', 'string' );
		$search 			= $this->_db->getEscaped( trim(JString::strtolower( $search ) ) );

		$where = array();

		//$where[] = 'p.group_id <> 1 ';
		$where[] = 'p.deleted = 0';
		$where[] = 'u.block = 0';

		if($user->gid < 25) {

			$canView	= Ownservice::checkAccess('user','view','user','all');

			if($canView) {
				$ownuser = &Ownservice::getUser();
				$level = $ownuser->get('level_id');

				if( $level > 1 && $level < 5 ) {
					$where[] = ' p.branch_id ='.$ownuser->get('branch_id');
					$where[] = ' p.group_id = 2';
				} else if($level == 5) {
					$where[] = ' ( p.group_id > 1 AND p.group_id < 5)';
				} else if($level == 6) {
					$where[] = 'p.group_id <> 1';
				}
			}
		} else {
			$where[] = 'p.group_id <> 1';
		}

		if($filter_branch){
			$where[] = 'p.branch_id='.$filter_branch;
		}

		if($filter_group) {
			$where[] = 'p.group_id='.$filter_group;
		}

		if($search){
			$where[] = ' ( LOWER( u.username ) LIKE '.$this->_db->Quote( '%'.$this->_db->getEscaped( $search, true ).'%', false ).
						' OR LOWER( u.name ) LIKE '.$this->_db->Quote( '%'.$this->_db->getEscaped( $search, true ).'%', false ) .
						' OR LOWER( p.firstname ) LIKE '.$this->_db->Quote( '%'.$this->_db->getEscaped( $search, true ).'%', false ) .
						' OR LOWER( p.lastname ) LIKE '.$this->_db->Quote( '%'.$this->_db->getEscaped( $search, true ).'%', false ) .
						' OR LOWER( p.phone_no ) LIKE '.$this->_db->Quote( '%'.$this->_db->getEscaped( $search, true ).'%', false ) .
						' OR LOWER( u.email ) LIKE '.$this->_db->Quote( '%'.$this->_db->getEscaped( $search, true ).'%', false ).')';
		}

		$where 		= ( count( $where ) ? ' WHERE ' . implode( ' AND ', $where ) : '' );

		return $where;
	}

	/**
	 * Method to remove a user
	 *
	 * @access public
	 * @return boolean true on success
	*/
	function delete($id){

		// Check for request forgeries
		JRequest::checkToken() or jexit( 'Invalid Token' );

		/*$query="DELETE FROM #__ownservice_users WHERE user_id=".$id; */
		$query = 'UPDATE #__ownservice_users SET deleted=1 WHERE id='.$id;
				
		$this->_db->setQuery($query);
		if(!$this->_db->query()){
			$this->setError($this->_db->getErrorMsg());
			return false;
		}

		return true;
	}

	/**
	 * Method to get branches all
	 *
	 * @return object
	 * @since 1.5
	*/
	function getBranches() {
		$query = ' SELECT * FROM #__ownservice_branches  '
				.' WHERE deleted=0 AND published = 1'
				.' ORDER BY name';

		$this->_db->setQuery($query);
		$branches = $this->_db->loadObjectList();

		return $branches;
	}

	/**
	 * Method to get groups all
	 *
	 * @return object
	 * @since 1.5
	*/
	function getGroups() {

		/*$query = ' SELECT id, name '
				.' FROM #__ownservice_groups '
				.' WHERE name <> '.$this->_db->Quote('Member')
				.' ORDER BY id ASC '
				;
		$this->_db->setQuery($query);
		$groups = $this->_db->loadObjectList();
		return $groups;*/
		// Initialise variables
		$user		= & JFactory::getUser();
		$ownuser	= & Ownservice::getUser();

		//get var
		$level = $ownuser->get('level_id');

		$where = '';
		
		if($level == 4) {
			$where = ' AND id=2 ';
		} else if($level == 5) {
			$where = ' AND ( id=2 OR id=3 or id=4 )';
		}

		$query = 'SELECT id, name'
				. ' FROM #__ownservice_groups '
				.' WHERE name <> '.$this->_db->Quote('Member')
				.$where
				. ' ORDER BY id ASC'
				;
		$this->_db->setQuery($query);
		$groups = $this->_db->loadObjectList();

		return $groups;
	}

	/**
	 * Method get user
	 *
	 * @return object
	 * @since 1.5
	*/
	function getUser($id) {

		$query = ' SELECT p.*, u.name FROM #__ownservice_users AS p '
				.' LEFT JOIN #__users AS u ON u.id=p.user_id '
				.' WHERE u.id='.$id.' AND u.block = 0 ';
		$this->_db->setQuery($query);
		$profile = $this->_db->loadObject();

		return $profile;
	}
}